package com.example.schoolassistant_android.net.model;

import android.util.Log;

import com.example.schoolassistant_android.base.BaseMode;
import com.example.schoolassistant_android.domain.LoginData;
import com.example.schoolassistant_android.domain.request.RequestLoginData;
import com.example.schoolassistant_android.net.GetDataInterface;
import com.example.schoolassistant_android.net.LoggingInterceptor;
import com.example.schoolassistant_android.net.ModelCallBack;
import com.example.schoolassistant_android.utils.JavaBeanUtil;
import com.example.schoolassistant_android.utils.RetrofitUtil;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import okhttp3.OkHttpClient;

/**
 * 所属包：com.example.schoolassistant_android.net.model
 * 作者：Administrator on 2020/8/18 14:58
 * 邮箱：tzw1109296630@163.com
 *
 */
public class LoginModel extends BaseMode {

    public void getLoginData(String tel, String pwd, String sign, String uuid,  final ModelCallBack.LoginCallBack callBack) {
        //使用okhttp请求,添加拦截器时把下面代码解释
        OkHttpClient ok = new OkHttpClient.Builder()
                .connectTimeout(20000, TimeUnit.SECONDS)
                .writeTimeout(20000, TimeUnit.SECONDS)
                .readTimeout(20000, TimeUnit.SECONDS)
                .addInterceptor(new LoggingInterceptor())
                .build();

        //使用Retrofit结合RxJava，okhttp封装类的单例模式
        Map<String, Object> map = new HashMap<>();
        map.put("phoneNo", tel);
        map.put("passWord", pwd);
        map.put("sign", sign);
        map.put("uuid", uuid);
        RequestLoginData requestLoginBean = JavaBeanUtil.map2Object(map, RequestLoginData.class);
        Log.d("aaa",requestLoginBean.toString());
        RetrofitUtil.getInstance(baseUrl, ok)
                .setCreate(GetDataInterface.class)
                .login(requestLoginBean)
                .subscribeOn(Schedulers.io())               //请求完成后在io线程中执行
                .observeOn(AndroidSchedulers.mainThread())  //最后在主线程中执行

                //进行事件的订阅，使用Consumer实现
                .subscribe(new Consumer<LoginData>() {
                    @Override
                    public void accept(LoginData loginBean) throws Exception {
                        //请求成功时返回数据
                        callBack.success(loginBean);
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        throwable.printStackTrace();
                        callBack.failed(throwable);
                    }
                });
    }
}
